package com.iexbuy.ihg.ui.fragment;

import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.iexbuy.ihg.R;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.entity.CoinHistoryListObject;
import com.iexbuy.ihg.entity.XiaoFeiOrderConfirmObject;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.pay.PayUtil;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.iexbuy.ihg.utils.ToastUtils;
import com.iexbuy.ihg.utils.UnitUtils;
import com.iexbuy.ihg.wxapi.WXPayEntryActivity;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.math.BigDecimal;
import java.util.HashMap;

public class WeDeCoinBuyingFragment extends BaseFragment {

	private static WeDeCoinBuyingFragment homeFragmentInstent;

	@ViewInject(R.id.msgListLayout)
	private PullToRefreshLayout msgListRefreshLayout;
	@ViewInject(R.id.itemAmount)
	private EditText itemAmount;
	@ViewInject(R.id.changeCoinAmount)
	private TextView changeCoinAmount;
	@ViewInject(R.id.payMethodGroup)
	private RadioGroup payMethodGroup;
	@ViewInject(R.id.cashBalancePay)
	private RadioButton cashBalancePay;
	@ViewInject(R.id.aliyPay)
	private RadioButton aliyPay;
	@ViewInject(R.id.weixingPay)
	private RadioButton weixingPay;
	@ViewInject(R.id.submitPayBtn)
	private Button submitPayBtn;

	private static XiaoFeiOrderConfirmObject xiaoFeiOrderConfirmObject;
	private int selectPayMethod = -1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_wede_coin_buy, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		mBaseActivity.setTitle(getResources().getString(R.string.we_de_coins_buy));
		mBaseActivity.setTitleLayoutVisibility(true);
		mBaseActivity.setHomeActivity(false);

		initRadioBtn();

		payMethodGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup radioGroup, int id) {
				String tag = radioGroup.findViewById(id).getTag().toString();
				selectPayMethod = Integer.valueOf(tag);
				submitPayBtn.setEnabled(true);
			}
		});
		submitPayBtn.setEnabled(false);

		itemAmount.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
			}

			@Override
			public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
				calculatPayment();
			}

			@Override
			public void afterTextChanged(Editable editable) {
			}
		});
	}

	private void calculatPayment() {
		String amoutValue = itemAmount.getText().toString();
		if (StringUtil.isNotEmpty(amoutValue)) {
			changeCoinAmount.setText(new BigDecimal(amoutValue).multiply(new BigDecimal("0.1")).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
		}
	}

	@OnClick(R.id.submitPayBtn)
	public void submitPayBtnClick(View view) {
		if (StringUtil.isEmpty(itemAmount.getText().toString())) {
			ToastUtils.toast(mBaseActivity, "请输入购买数量");
			return;
		}
		if (selectPayMethod == -1) {
			ToastUtils.toast(mBaseActivity, "请选择支付方式");
			return;
		}
		submitGoldCoinBuyOrder();
	}

	private void submitGoldCoinBuyOrder() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("money", itemAmount.getText().toString());//金币数量
		paramMap.put("rechargeType", "gold");
		if (selectPayMethod == 0) {
			paramMap.put("useBalance", "Y");
		}
		ServiceHelper.send(mBaseActivity, ServiceHelper.SUBMIT_GOLD_COIN_BUY_ORDER, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						mBaseActivity.showDialog("提交中...");
					}

					@Override
					public void onCancelled() {
						mBaseActivity.closeDialog();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						mBaseActivity.closeDialog();
						xiaoFeiOrderConfirmObject = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), XiaoFeiOrderConfirmObject.class);
						CommUtil.showAlert(mBaseActivity, "下单成功", "下单成功，即将跳到支付界面", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialogInterface, int i) {
								handlePay();
							}
						});
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						mBaseActivity.closeDialog();
						ToastUtils.toast(mBaseActivity, msg);
					}
				});
	}

	private void handlePay() {
		switch (selectPayMethod) {
			case 0:
				ToastUtils.toast(mBaseActivity, "恭喜，支付成功！");
				mBaseActivity.finish();
				break;
			case 1:
				PayUtil.requestAlipay(mBaseActivity,
						xiaoFeiOrderConfirmObject.getName(),
						xiaoFeiOrderConfirmObject.getId(),
						xiaoFeiOrderConfirmObject.getOrderNo(),
						xiaoFeiOrderConfirmObject.getPayMoney(),
						new PayUtil.OnPayCompleteListener() {
							@Override
							public void onPayComplete(String resultStr) {
								ToastUtils.toast(mBaseActivity, "恭喜，支付成功！");
								mBaseActivity.finish();
							}
						});
				break;
			case 2:
				WXPayEntryActivity.setOnPayCompleteListener(new PayUtil.OnPayCompleteListener() {
					@Override
					public void onPayComplete(String resultStr) {
						ToastUtils.toast(mBaseActivity, "恭喜，支付成功！");
						mBaseActivity.finish();
					}
				});
				PayUtil.requestWeixinpay(mBaseActivity,
						xiaoFeiOrderConfirmObject.getOrderNo(),
						xiaoFeiOrderConfirmObject.getName(),
						"金币",
						xiaoFeiOrderConfirmObject.getPayMoney(),
						"");
				break;
			default:
				break;
		}
	}

	private void initRadioBtn() {
		int iconSize = UnitUtils.dip2px(mBaseActivity, 32);
		int radioSize = UnitUtils.dip2px(mBaseActivity, 40);
		Drawable drawable1l = getResources().getDrawable(R.drawable.pay_money);
		drawable1l.setBounds(0, 0, iconSize, iconSize);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
		Drawable drawable1r = getResources().getDrawable(android.R.drawable.btn_radio);
		drawable1r.setBounds(0, 0, iconSize, radioSize);
		cashBalancePay.setCompoundDrawables(drawable1l, null, drawable1r, null);//只放左右

		Drawable drawable2l = getResources().getDrawable(R.drawable.pay_alipay);
		drawable2l.setBounds(0, 0, iconSize, iconSize);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
		Drawable drawable2r = getResources().getDrawable(android.R.drawable.btn_radio);
		drawable2r.setBounds(0, 0, iconSize, radioSize);
		aliyPay.setCompoundDrawables(drawable2l, null, drawable2r, null);//只放左右

		Drawable drawable3l = getResources().getDrawable(R.drawable.pay_wechat);
		drawable3l.setBounds(0, 0, iconSize, iconSize);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
		Drawable drawable3r = getResources().getDrawable(android.R.drawable.btn_radio);
		drawable3r.setBounds(0, 0, iconSize, radioSize);
		weixingPay.setCompoundDrawables(drawable3l, null, drawable3r, null);//只放左右
	}

	/**
	 * @return the homeFragmentInstent
	 */
	public static WeDeCoinBuyingFragment getHomeFragmentInstent() {
		return homeFragmentInstent;
	}

}
